package com.carryking.smart.rpc.utils;

import com.carryking.smart.rpc.constant.RespStatusConstant;
import com.carryking.smart.rpc.entity.RequestEntity;
import com.carryking.smart.rpc.entity.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by jincarry on 2018/1/11.
 */
@Slf4j
public class ServerInvokUtils {

    private static ApplicationContext context;

    public static void setContext(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    public static ResponseEntity invok(RequestEntity requestEntity) {
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setRequestId(requestEntity.getRequestId());
        responseEntity.setCode(RespStatusConstant.EXCEPTION);
        try {
            Class clasz = ClassLoader.getSystemClassLoader().loadClass(requestEntity.getClassName());
            Object object = context.getBean(clasz);
            Method method = clasz.getDeclaredMethod(requestEntity.getMethodName(),requestEntity.getParamsClass());
            Object result = method.invoke(object, requestEntity.getParams());

            responseEntity.setCode(RespStatusConstant.SUCCESS);
            responseEntity.setMsg("success");
            responseEntity.setRespClass(result.getClass());
            responseEntity.setRespBody(result);
            if (log.isDebugEnabled()) {
                log.debug("服务请求调用RequestEntity={},ResponseEntity={}",requestEntity,responseEntity);
            }
            return responseEntity;
        } catch (ClassNotFoundException e) {
            log.warn("远程请求发生异常,RequestEntity={}",requestEntity,e);
            responseEntity.setMsg("service not found;service class not found");
            responseEntity.setException(e);
            return responseEntity;
        } catch (NoSuchMethodException e) {
            log.warn("远程请求发生异常,RequestEntity={}",requestEntity,e);
            responseEntity.setMsg("service not found;no such method");
            responseEntity.setException(e);
            return responseEntity;
        } catch (IllegalAccessException e) {
            log.warn("远程请求发生异常,RequestEntity={}",requestEntity,e);
            responseEntity.setException(e);
            responseEntity.setMsg("server error");
            return responseEntity;
        } catch (InvocationTargetException e) {
            log.warn("远程请求发生异常,RequestEntity={}",requestEntity,e);
            responseEntity.setMsg("server error");
            responseEntity.setException(e);
            return responseEntity;
        }
    }

}
